// 排序 + 双指针 时间复杂度 O(n*n) 空间复杂度 O(log n)

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        if (n < 3) return {};
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        int left, right;
        for (int i = 0; i < n - 2; i++) {
            left = i + 1;
            right = n - 1;
            while (left < right) {
                if (nums[i] + nums[left] + nums[right] == 0) {
                    ret.emplace_back(vector<int>{nums[i], nums[left], nums[right]});
                    while (left + 1 != n && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    left++;

                    while (right - 1 != -1 && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    right--;

                }
                else if (nums[i] + nums[left] + nums[right] < 0) {
                    left++;
                }
                else {
                    right--;
                }
            }
            while (i + 1 != n && nums[i] == nums[i + 1]) {
                i++;
            }
        }
        return ret;
    }
};